const mysql = require("mysql");

let options = {
  host: "localhost",
  user: "root",
  password: "root",
  port: "3306",
  database: "store",
};

const pool = mysql.createPool(options);

/**
 * @description: 封装数据库操作类
 */
module.exports = class Model {
  /**
   * @description: 通用的查询方法
   * @param {*} sql 要执行的语句
   * @param {*} params  sql语句占位符的参数数组
   * @return {*}
   */
  static query(sql, params) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => {
        if (err) {
          connection.release();
        } else {
          connection.query(sql, params, (err, results) => {
            if (err) {
              reject(err);
            } else {
              resolve(results);
            }
            connection.release();
          });
        }
      });
    });
  }

  static getNowAndLastDate() {
    let date = new Date();
    let month = (date.getMonth() + 1 + "").padStart(2, 0);
    let newDate = "" + date.getFullYear() + month + date.getDate();
    let lastDate = "" + date.getFullYear() + month + (date.getDate() + 1);

    var fullYear = date.getFullYear();
    var endOfMonth = (new Date(fullYear, month, 0).getDate() + "").padStart(2,0); // 获取本月最后一天
    let nowMonth = "" + date.getFullYear() + "-" + month + "-01 00:00:00";
    let lastMonth = "" + date.getFullYear() + "-" + month + `-${endOfMonth} 23:59:59`;
    return {
      newDate,
      lastDate,
      nowMonth,
      lastMonth,
    };
  }
};
